<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 2015/2/28
 * Use : ...
 * File: DbHelper.php
 */

namespace ulue\core\db\helper;

abstract class DbHelper
{
    /**
     *  解析转义的表名，给表名加上前缀
     * before: "SELECT * FROM [[admin]] a INNER JOIN [[tag]] b ON a.id=b.ie [[uid]]"
     * after : "SELECT * FROM pre_admin a INNER JOIN pre_tag b ON a.id=b.ie pre_uid"
     */
    static public function resolveTableName($sql, $tblPrefix)
    {
        $sql = trim($sql);

        if (!$sql)
        {
            return '';
        }

        $reg = '/\[{2}\w+\]{2}/i';

        if ( preg_match_all($reg, $sql, $matches) )
        {
            $reals = [];

            foreach ($matches[0] as $name)
            {
                $reals[] = $tblPrefix.trim($name, '[]');
            }

            return str_replace($matches[0], $reals, $sql);
        }

        return $sql;
    }


    /**
     * 前缀检查，即检查表名是否是完整表名称 存在前缀 return true
     * @param $tableName
     * @return bool
     */
    static public function hasPrefix($tableName, $prefix='')
    {
        # 无前缀，不用检查
        if (!$prefix)
        {
            return true;
        }

        $tableName = trim($tableName);

        return (strpos($tableName, $prefix )===0);
    }

}// end class DbHelper